package cn.springboot.erp.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.springboot.erp.commons.QueryParams;
import cn.springboot.erp.commons.ResponseResult;
import cn.springboot.erp.entity.SalesReturns;
import cn.springboot.erp.service.SalesReturnsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

@RestController
@RequestMapping("return")
@Api(tags = "退货管理")
public class ReturnController {

    @Resource
    private SalesReturnsService salesReturnsService;

    @ApiOperation("数据分页")
    @PostMapping("page")
    public ResponseResult listPage(@RequestBody QueryParams<SalesReturns> queryParams){
        return salesReturnsService.listPage(queryParams);
    }

    @ApiOperation("根据id查询")
    @GetMapping("selectById/{id}")
    public ResponseResult selectById(@PathVariable("id") Integer id){
        SalesReturns one = salesReturnsService.getById(id);
        return ResponseResult.Success().data("one",one);
    }

    @ApiOperation("根据id删除")
    @GetMapping("deleteById/{id}")
    public ResponseResult deleteById(@PathVariable("id") Integer id){
        return salesReturnsService.deleteById(id);
    }

    @ApiOperation("修改状态")
    @GetMapping("state/{id}/{state}")
    public ResponseResult state(@PathVariable("id") Integer id,@PathVariable("state") Integer state){
        SalesReturns salesReturns = new SalesReturns();
        salesReturns.setId(id);
        salesReturns.setRefundStatus(state);
        salesReturnsService.updateById(salesReturns);
        return ResponseResult.Success().msg("修改成功");
    }

    @ApiOperation("添加或编辑")
    @PostMapping("insertOrUpdate")
    public ResponseResult insertOrUpdate(@RequestBody SalesReturns salesReturns){
        Integer orderId = salesReturns.getOrderId();
        LambdaQueryWrapper<SalesReturns> lambda = new QueryWrapper<SalesReturns>().lambda();
        lambda.eq(SalesReturns::getOrderId,orderId);
        SalesReturns one = salesReturnsService.getOne(lambda);
        if (ObjectUtils.isNotNull(one)){
            if (ObjectUtil.equal(one.getId(), salesReturns.getId())) {
                salesReturnsService.saveOrUpdate(salesReturns);
                return ResponseResult.Success().msg("修改成功");
            }
            return ResponseResult.Fail().msg("订单编号已经存在");
        }
        salesReturns.setReturnDate(new Date());
        salesReturnsService.saveOrUpdate(salesReturns);
        return ResponseResult.Success().msg("添加成功");
    }
}
